package com.shisan.tingshu.cdc.handler;

import com.shisan.tingshu.cdc.entity.CdcEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import top.javatool.canal.client.annotation.CanalTable;
import top.javatool.canal.client.handler.EntryHandler;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Component
@CanalTable("album_info") // 监听变更表
@Slf4j
public class CdcEntityHandler implements EntryHandler<CdcEntity> {

    @Autowired
    private StringRedisTemplate redisTemplate;

//    @Autowired
//    private RabbitService rabbitService;

    /**
     * 监听的表中有数据新增的时候，会回调该方法
     * @param cdcEntity
     */
    @Override
    public void insert(CdcEntity cdcEntity) {
        log.info("Canal客户端监听到了album_info表中有数据的新增的id：{}", cdcEntity.getId());
    }

    /**
     * 监听的表中有数据变更的时候，会回调该方法
     * @param before 修改之前的老数据
     * @param after 修改后的新数据
     */
    @Override
    public void update(CdcEntity before, CdcEntity after) {
        log.info("Canal客户端监听到了album_info表中有数据的修改，修改之前的id：{}", before.getId());
        log.info("Canal客户端监听到了album_info表中有数据的修改，修改之后的id：{}", after.getId());
        String cacheKey = "cache:info:" + after.getId();
        // 创建一个线程池
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2);
        // 延迟300毫秒删除缓存
        try {
            scheduledExecutorService.schedule(new Runnable() {
                @Override
                public void run() {
                    redisTemplate.delete(cacheKey);
                }
            }, 300, TimeUnit.MICROSECONDS);

        } catch (Exception e) {
            //  TODO  使用MQ进行重试删除操作
//            rabbitService.sendMessage()
        }
    }

    /**
     * 监听的表中有数据删除的时候，会回调该方法
     * @param cdcEntity 删除的对象
     */
    @Override
    public void delete(CdcEntity cdcEntity) {
        log.info("Canal客户端监听到了album_info表中有数据的删除，删除的数据的id：{}", cdcEntity.getId());
    }
}